import { makeAutoObservable } from 'mobx'
import * as _ from 'lodash-es'
import { selectTreeNodes } from '../utils/treeHandler'

class Store {
	constructor() {
		makeAutoObservable(this, undefined, { autoBind: true })
	}

	// 展开全部
	isOpenAll = false
	// 选中全部
	isCheckedAll: any = false
	// 选中节点
	checkedNodes: any = []

	// 树数据
	_treeData = []
	get treeData() {
		return this._treeData
	}
	setTreeData(data: any) {
		this._treeData = data
	}

	//展开节点
	_expandTreeLeafs = []
	get expandTreeLeafs() {
		return this._expandTreeLeafs
	}
	setExpandTreeLeafs(data: any) {
		this._expandTreeLeafs = data
	}

	// 选中节点
	_checkedLeafs = []
	get checkedLeafs() {
		return this._checkedLeafs
	}
	setCheckedLeafs(data: any) {
		this._checkedLeafs = data
	}

	// 搜索值
	_searchValue = ''
	get searchValue() {
		return this._searchValue
	}
	set searchValue(data: any) {
		this._searchValue = data
	}

	// 选中某个节点
	onCheck(checked: any, checkNode: any) {
		checkNode.checked = !checkNode.checked
		if (checkNode.checked) {
			this.checkedNodes.push(checkNode)
		} else {
			this.checkedNodes.pop()
		}
		this.setCheckedLeafs(selectTreeNodes(this.checkedNodes))
		this.isCheckedAll = checked.length === selectTreeNodes(this.checkedNodes).length && checked.length !== 0
		if (_.isEmpty(checked)) {
			this.checkedNodes = []
			this.setCheckedLeafs([])
		}
	}

	// 选中全部节点
	onCheckAll(e: any) {
		const isChecked = e.target?.checked

		// 直接更新 checkedNodes
		this.checkedNodes = isChecked ? [...this.treeData] : []

		// 计算当前选中的节点数量
		const selectedLeafs = selectTreeNodes(this.checkedNodes)
		const totalLeafs = selectTreeNodes(this.treeData)

		// 更新是否全选状态
		this.isCheckedAll = selectedLeafs.length === totalLeafs.length

		// 直接设置选中的叶子节点
		this.setCheckedLeafs(selectedLeafs)
		// console.log(JSON.stringify(treeStore.treeData))
	}

	// 搜索节点
	onSearch(searchValue: any) {
		console.log(searchValue)
	}
}

export const treeStore = new Store()

export default Store
